<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- 紧急返件回运 - 编辑 -->
    <BreakSpace label="质量信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel ref="formPanel1" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false"
               @formChange="formChangeHandle"/>
    <div style="margin-bottom: 1rem;"></div>
    <BreakSpace label="返件信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FilterTable
      ref="table3"
      :columns="columns"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="false"
      height="auto"
      :isPagination='false'
    >
    </FilterTable>
    <BreakSpace label="回运信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel ref="formPanel3" :list="formList2" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false"
              />
    <FormPanel ref="formPanel2" :list="formList3" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false"
               @formChange="formChangeHandle2"/>
    <div style="padding-top: 3rem;"></div>
    <div
      :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" @click="closeDialog">关 闭</multiuse-button>
      <multiuse-button type="primary" :click="saveDialog.bind()" :disabled="deleteFlag">保存</multiuse-button>

    </div>
    <div style="margin-bottom: 1rem;"></div>
  </div>
  </Spin>
</template>
<script>
  import {getPartType} from '@/api/claim/dealer/QualityInformationManagement_DLR/EmergencyReturn/index';
  import {inStockByPtId,quyrpQaUrgent} from '@/api/claim/factory/QualityInformationManagement_OEM/CoreIssueStockInOut/index';
  import {editSave} from '@/api/claim/factory/QualityInformationManagement_OEM/CoreIssueRules';
  import { isFormEmpty } from '@/utils/index';
  import { dictionary } from '@/utils/dictMixin';
  export default {
    mixins: [dictionary],
    props: ['rowData'],
    components: {
    },
    data() {
      return {
        loading: false,
        editRow: {},
        dataList: [],
        collapse: false,
        urgentStatusFlag: 5,
        infoId: null,
        fetchParams: {}, //ipa 接口
        selectedRows: [], //选中经销商
        formList: this.createFormList(),
        formList2: this.createFormList2(),
        formList3: this.createFormList3(),
        columns: this.creatHeader(),
        saveData: null,
        saveData1: null,
        flag:true,
        deleteFlag:true
      };
    },
    async created() {
      this.loading = true;
      await this.chuqi();
      await this.getDetailFun(this.rowData.urgentId);
      if(this.rowData.urgentStatus ==55651001 || this.rowData.urgentStatus ==55651003 ){
        this.deleteFlag = false;
      }
      if(this.rowData.statusStr =='已回运'){
        this.formList.find(x => x.fieldName == 'str').hidden = false;
        this.formList.find(x => x.fieldName == 'str').initialValue = this.rowData.statusStr;
        this.flag = false;
        this.deleteFlag = true;
      }else{
        this.formList.find(x => x.fieldName == 'str').hidden = true;
        this.formList.find(x => x.fieldName == 'urgentStatus').hidden = false;
      }

      this.loading = false;
    },
    methods: {
      //考核类型
      async chuqi() {
        // const res = await getPartType({ type: 5521 });
        // if (res.resultCode == 200) {
        //   this.formList3.find(x => x.fieldName == 'expressType').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        // }
        const res1 = await getPartType({ type: 5568 });
        if (res1.resultCode == 200) {
          this.columns.find(x => x.dataIndex === 'inRemarks').editItems = res1.data.map(x => ({ text: x.codeCnDesc, value: x.codeCnDesc }));
        }
        // const res2 = await getPartType({ type: 5567 });
        // if (res2.resultCode == 200) {
        //   this.columns.find(x => x.dataIndex === 'dtlStatus').editItems = res2.data.map(x => ({ text: x.codeCnDesc, value: x.codeId }));
        // }
        // const res3 = await getPartType({type: 5564});
        // if (res3.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'dataSource').itemList = res3.data.map(y => ({
        //     text: y.codeCnDesc,
        //     value: y.codeId
        //   }));
        // }
        // const res4 = await getPartType({type: 5565});
        // if (res4.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'urgentStatus').itemList = res4.data.map(y => ({
        //     text: y.codeCnDesc,
        //     value: y.codeId
        //   }));
        // }
        // const res5 = await getPartType( {type:5500});
        // if (res5.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'isKeep').itemList = res5.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        // }
      },
      delsFunXj(data) {
        this.$refs.table3.$refs.pageTable.EXECUTE_DELETE([data]);
      },
      //保存
      async saveDialog() {
        this.$refs.formPanel1.SUBMIT_FORM();
        this.$refs.formPanel2.SUBMIT_FORM();
        this.saveData = Object.assign(this.saveData, this.saveData1);

        let arr2 = [];
        this.$refs.table3.$refs.pageTable.list.map(x => {
          delete  x.dtlId;
          arr2.push(x);
        });
        this.editRow.dtlList = arr2;
        this.editRow.delDtlIds = this.partIds;
        if (this.saveData &&this.saveData1) {
          this.loading = true;
          let res = await editSave(this.editRow);
          if (res.resultCode === 200) {
            this.closeDialog('refresh');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
            this.$emit('save');
          } else {
            this.loading = false;
            this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
            this.closeDialog();
          }
        }
      },
      async getDetailFun(val) {
        let res= await quyrpQaUrgent({id : val});
        this.editRow = res.data;
        //为form赋值
        for (let i in res.data) {
          this.formList.map(x => {
            if (x.fieldName == i) {
              x.initialValue = res.data[i];
            }
          });
        }
        for (let i in res.data) {
          this.formList2.map(x => {
            if (x.fieldName == i) {
              x.initialValue = res.data[i];
            }
          });
        }
        for (let i in res.data) {
          this.formList3.map(x => {
            if (x.fieldName == i) {
              x.initialValue = res.data[i];
            }
          });
          this.formList3.forEach(x => {
            x.initialValue = res.data[x.fieldName];
            if (x.fieldName == 'fileList') {
              x.initialValue = res.data.fileList.map((f) => ({ name: f.title, url: f.fileUrl }));
            }
          });
        }


        let fileIds = [];
        res.data.fileList.map(x =>{
          fileIds.push(x.fileId);
        });
        let idsss = '';
        fileIds.map(x => {
          idsss += x + ','
        });
        this.fileIds = idsss;
        //为table赋值
        if (200 == res.resultCode) {
          let data = res.data;
          if (isFormEmpty(data)) {
            data = {};
          }
          let records = data.dtlList;
          // for(let i =0;i<records.length;i++){
          //   records[i].inRemarks == null ? null : Number(records[i].inRemarks);
          // }
          console.log(records);
          if (isFormEmpty(records)) {
            records = [];
          }
          this.$refs.table3.$refs.pageTable.EXECUTE_INSERT(records);
          let iss = '';
          this.$refs.table3.$refs.pageTable.list.map((x) => {
            iss += x.dtlId + ','
          });
          this.partIds = iss;
        }


      },
      formChangeHandle2(val) {
        this.saveData = val;
      }, formChangeHandle(val) {
        this.saveData1 = val;
      },
      //搜索获取数据
      changeHandle(val) {
        this.fetchParams = val;
        console.log(val);
      },
      //选中
      selectChange(rows) {
        this.selectedRows = rows;
        console.log(this.selectedRows);
      },
      //取消操作
      closeDialog() {
        this.$emit('close', {visible: false, data: this.selectedRows, type: 'close'});
      },
      //table表头和数据源
      creatHeader() {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 60,
            fixed: 'left',
            render: props => {
              return (
                <div style="text-align:center">
                  <multiuse-button type="text" onClick={() => this.delsFunXj(props.row)} disabled={this.deleteFlag}>
                    删除
                  </multiuse-button>
                </div>
              );
            }
          },
          { title: '配件代码', dataIndex: 'partCode', sorter: true },
          { title: '配件名称', dataIndex: 'partName', sorter: true },
          { title: '单位', dataIndex: 'partUnit', sorter: true },
          { title: '数量', dataIndex: 'partCount', sorter: true },
          { title: '收件人', dataIndex: 'receiver', sorter: true,editable: true, },
          { title: '收件人电话', dataIndex: 'receiverTel', sorter: true ,editable: true,},
          { title: '收件地址', dataIndex: 'receiverAddress', sorter: true,editable: true, },
          {
            title: '入库数量',
            dataIndex: 'inCount',
            minWidth: 90,
            sorter: true,
            editable: false,
            showOverflowTooltip: true,
            editRequired: false,
            editType: 'number',
            editValidator:(val, row, callback) => {
              if(row.inCount>0){
                if (row.inCount > row.partCount) {
                  this.$notify.error({ title: '提示信息', message: '已超过配件数量(' + row.partCount + ')' || '操作失败!' });
                  row.inCount = 1
                }
              }else{
                this.$notify.error({ title: '提示信息', message: '入库数量不能为负数' || '操作失败!' });
                row.inCount = 1
              }

            }
          }, {
            title: '旧件状态',
            dataIndex: 'dtlStatus',
            minWidth: 90,
            sorter: true,
            editable: false,
            showOverflowTooltip: true,
            editType: 'select',
            editItems: this.createDictList('5567'),
          }, {
            title: '入库说明',
            dataIndex: 'inRemarks',
            minWidth: 90,
            sorter: true,
            editable: false,
            showOverflowTooltip: true,
            editType: 'select',
            editItems: []
          },
        ];
      },
      //基本信息
      createFormList() {
        return [
          {
            type: 'INPUT',
            label: '紧急返件单号',
            fieldName: 'urgentNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '质量报告单号',
            fieldName: 'reportNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '数据来源',
            fieldName: 'dataSource',
            readonly: true,// 只读
            disabled: true, // 置会
            itemList: this.createDictList('5564'),
          },
          {
            type: 'INPUT',
            label: '经销商代码',
            fieldName: 'dealerCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '经销商名称',
            fieldName: 'dealerName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '紧急返件单状态',
            fieldName: 'str',
            readonly: true,// 只读
            disabled: true, // 置会
            hidden:false
          },
          {
            type: 'SELECT',
            label: '紧急返件单状态',
            fieldName: 'urgentStatus',
            readonly: true,// 只读
            disabled: true, // 置会
            itemList: this.createDictList('5565'),
            hidden:true
          },
          {
            type: 'INPUT',
            label: '维修工单号',
            fieldName: 'roNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: 'VIN',
            fieldName: 'vin',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '索赔单号',
            fieldName: 'cmsClaimNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '生产日期',
            fieldName: 'prodDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '销售日期',
            fieldName: 'saleDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '行驶里程',
            fieldName: 'driveMile',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '维修开始时间',
            fieldName: 'serviceBeginDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '主损件',
            fieldName: 'partCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '主损件名称',
            fieldName: 'partName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '维修结束时间',
            fieldName: 'serviceEndDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '故障现象代码',
            fieldName: 'faultCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '故障现象描述',
            fieldName: 'faultName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '车型名称',
            fieldName: 'modelName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '是否留车',
            fieldName: 'isKeep',
            placeholder: '请输入...',
            disabled:true,
            itemList: this.createDictList('5500'),
          },
          {
            type: 'INPUT',
            label: '留车单号',
            fieldName: 'keepCar',
            placeholder: '请输入数量...',
            disabled: true, // 置会
          },
        ];
      },
      createFormList2() {
        return [

          {
            type: 'INPUT',
            label: '返件要求说明',
            fieldName: 'urgentRemarks',
            selfCols: 3,// 元素占据几行
            rows: 1,
            readonly: true,// 只读
            disabled: true // 置会
          }
        ];
      },
      createFormList3() {
        return [
          {
            type: 'SELECT',
            label: '运输方式',
            fieldName: 'expressType',
            itemList: this.createDictList('5521'),
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '物流公司',
            fieldName: 'expressName',
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '物流单号',
            fieldName: 'expressNo',
            disabled: true // 置会
          },
          {
            type: 'DATE',
            label: '回运时间',
            fieldName: 'expressDate',
            placeholder: '选择回运时间',
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '邮寄人',
            fieldName: 'expressUser',
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '邮寄人电话',
            fieldName: 'expressTel',
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '邮寄说明',
            fieldName: 'expressRemarks',
            selfCols: 3,// 元素占据几行
            rows: 1,
            disabled: true // 置会
          },
          {
            type: 'UPLOAD_FILE',
            label: '上传文件',
            fieldName: 'fileList',
            placeholder: '上传文件...',
            initialValue: [],
            disabled: true,
            upload: {
              actionUrl: '/api/file/oss/upload',
              limit: 2,
              // tipText: '只能上传pdf格式'
            }
          },
          {
            type: 'INPUT',
            label: '入库说明',
            fieldName: 'inRemark',
            selfCols: 3,// 元素占据几行
            rows: 2,
          }
        ];
      },

    }
  };
</script>

<style lang="less" scoped></style>
